import Router from 'koa-router';
const router = new Router();
const { DataTypes, Sequelize } = require('sequelize')
const sequelize = new Sequelize('2206a', 'root', 'root', {
    host: 'localhost',
    dialect: 'mysql'/* 选择 'mysql' | 'mariadb' | 'postgres' | 'mssql' 其一 */
});
const User = sequelize.define('username', {
    id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    // 在这里定义模型属性
    name: {
        type: DataTypes.STRING,
        // allowNull: false
    },
    unit: {
        type: DataTypes.STRING
    },
    defaults: {
        type: DataTypes.STRING
    },
    duty: {
        type: DataTypes.STRING
    },
    mail: {
        type: DataTypes.STRING
    }
}, {
    // 这是其他模型参数
    timestamps: false,
    freezeTableName: true
});
(async () => {
    await sequelize.sync();
})();
const get_list = async (ctx: Router.RouterContext, next: any) => {
    const users = await User.findAll();
    ctx.body = { code: 200, data: users };
};
router.get('/get_list', get_list);

const add_list = async (ctx: Router.RouterContext, next: any) => {
    // console.log(ctx.request.body);
    let { unit, name, duty, mail, defaults }: any = ctx.request.body
    const jane = await User.create({ name, unit, duty, mail, defaults });
    if (jane) {
        ctx.body = { code: 200 };
    }
};
router.post('/add_list', add_list);

const set_list = async (ctx: Router.RouterContext, next: any) => {
    // console.log((ctx.request.body as any).id);
    let { unit, name, duty, mail, defaults }: any = (ctx.request.body as any).addList
    let id = (ctx.request.body as any).id

    let jane = await User.update({ name, unit, duty, mail, defaults }, {
        where: {
            id
        }
    });
    if (jane) {
        ctx.body = { code: 200 };
    }
};
router.post('/set_list', set_list);


const del_list = async (ctx: Router.RouterContext, next: any) => {
    console.log(ctx.request.body);
    let id=ctx.request.body
    let jane=await User.destroy({
        where: {id}
      });
      if (jane) {
        ctx.body = { code: 200 };
    }
};
router.delete('/del_list', del_list);


export default router;
